package com.company.managesystem.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.company.managesystem.viewholder.ListViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于listview的Adapter
 * Created by lqy on 2017/7/17.
 */

public abstract class ListViewAdapter<D> extends BaseAdapter {
    /**
     *数据集
     **/
    protected final List<D> mDataSet = new ArrayList<>();
    /**
     * Item Layout
     */
    private int mImtemLayoutId;

    public ListViewAdapter(){}

    /**
     * @param layoutId
     */
    public ListViewAdapter(int layoutId){
        mImtemLayoutId = layoutId;
    }

    public ListViewAdapter(int layoutId , List<D> datas){
        mImtemLayoutId = layoutId;
        mDataSet.addAll(datas);
    }

    /**
     * @param item
     */
    public void addItem(D item){
        mDataSet.add(item);
        notifyDataSetChanged();
    }

    /**
     * @param items
     */
    public void addItems(List<D> items){
        mDataSet.addAll(items);
        notifyDataSetChanged();
    }

    /**
     * @param item
     */
    public void addItemToHead(D item){
        mDataSet.add(item);
        notifyDataSetChanged();
    }

    /**
     * @param items
     */
    public void addItemToHead(List<D> items){
        mDataSet.addAll(0, items);
        notifyDataSetChanged();
    }

    /**
     * @param position
     */
    public void remove(int position){
        mDataSet.remove(position);
        notifyDataSetChanged();
    }

    /**
     * @param item
     */
    public void remove(D item){
        mDataSet.remove(item);
        notifyDataSetChanged();
    }

    /**
     * 清空Adapter
     */
    public void clear(){
        mDataSet.clear();
        notifyDataSetChanged();
    }

    /**
     * @return
     */
    @Override
    public int getCount() {
        return mDataSet.size();
    }

    /**
     * @param position
     * @return
     */
    public D getItem(int position){
        return mDataSet.get(position);
    }

    /**
     * @param position
     * @return
     */
    public long getItemId(int position){
        return position;
    }

    /**
     * 根据View Type返回布局资源
     *
     * @param type
     * @return
     */
    protected int getItemLayout(int type){
        return mImtemLayoutId;
    }

    /**
     * 封装getView逻辑，将根据viewType获取布局资源、解析布局资源、创建ViewHolder等逻辑封装起来,简化使用过程
     *
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int viewType = getItemViewType(position);
        ListViewHolder viewHolder = ListViewHolder.get(convertView , parent , getItemLayout(viewType));
        //绑定数据
        onBindData(viewHolder , position ,getItem(position));
        return viewHolder.getItemView();
    }

    protected abstract void onBindData(ListViewHolder viewHolder, int position, D item);
}
